<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        .box1{width:100px;height:100px;background: red;position: absolute;left:0;top:0;}
    </style>
</head>
<body>
    <div class="box1"></div>
</body>
<script>

    class Drag{
        constructor(ele){
            this.ele = ele;

            // 注意1：将事件处理函数封装之后的this指向，需要使用bind修改
            // 注意2：使用bind修改this指向后，绑定和删除事件时无法直接找到同一个事件处理函数，需要提前使用bind处理事件处理函数，将处理之后的事件处理函数提前保存起来，绑定事件和删除事件时通过保存起来的事件处理函数进行绑定和删除

            this.m = this.move.bind(this);
            this.u = this.up.bind(this);

            // 1. 先读可能存在的坐标位置
            this.getLocal()

            this.addEvent();
        }
        getLocal(){
            this.ele.style.left = (localStorage.getItem("left") || 0) + "px";
            this.ele.style.top = (localStorage.getItem("top") || 0) + "px";
        }
        addEvent(){
            this.ele.addEventListener("mousedown", this.down.bind(this));
        }
        down(eve){
            this.downE = eve || window.event;
            document.addEventListener("mousemove", this.m);
            document.addEventListener("mouseup", this.u);
        }
        move(eve){
            this.moveE = eve || window.event;
            this.ele.style.left = this.moveE.pageX - this.downE.offsetX + "px";
            this.ele.style.top = this.moveE.pageY - this.downE.offsetY + "px";
        }
        up(){
            document.removeEventListener("mousemove", this.m);
            document.removeEventListener("mouseup", this.u);

            // 2. 存储元素的当前位置
            localStorage.setItem("left", this.ele.offsetLeft);
            localStorage.setItem("top", this.ele.offsetTop);
        }
    }

    new Drag(document.querySelector(".box1"))
    
</script>
</html>